<template>
  <div class="editor-container">
    <div id="vditor" class="vditor"></div>
    <div class="sidebar">
      <h2>大纲</h2>
      <ul>
        <li v-for="(heading, index) in headings" :key="index" @click="scrollToHeading(heading)">
          {{ heading.text }}
        </li>
      </ul>
    </div>
    <div class="ai-result" ref="aiResultRef" v-show="isShowDaGang" style="top: 0;;">
      <div class="dagang-ai-content">
        <div class="dagang-ai-text" v-if="daGangText" v-html="daGangText" ref="daGangAiText"></div>
        <div class="dagang-ai-button" v-if="daGangText">
          <div class="dagang-res-button">
            <CloseCircleOutlined />
          </div>
          <div class="dagang-res-button">
            <RedoOutlined />
          </div>
          <div class="dagang-res-button">
            <CheckCircleOutlined />
          </div>
        </div>
      </div>
      <div class="title-input">
        <div class="dagang-icon">
          <BarsOutlined />
        </div>
        <div style="margin: 0 5px;">智能大纲：</div>
        <div>
          <input class="dagang-input" type="text" v-model="daGangSearchText" @keydown.enter="daGangInputEvent" placeholder="请告诉我你的专业和针对的项目类型" />
        </div>
        <div class="dagang-icon">
          <SendOutlined />
        </div>
      </div>
    </div>
    <div class="lianxiang" v-show="isShowLianXiang" ref="lianXiangRef" style="top: 0; left: 0;">
      <div class="lianxiang-icon" @click="toStartLianXiang" v-show="!isStartLianXiang">
        <img src="/sikao.png" alt="">
      </div>
      <div class="lianxiang-content" v-show="isStartLianXiang">
        <div class="lianxiang-header">
          <div>
            <img style="marginBottom: 12px;marginRight: 10px;" src="/yuyilianxiang.png" alt="" />
          </div>
          <div style="marginBottom: 12px;marginRight: 10px;" class="lianxiang-title">智能联想：</div>
          <div>
            <a-tabs v-model:activeKey="lianxiangActiveKey">
              <a-tab-pane key="1" tab="规范联想" force-render></a-tab-pane>
              <a-tab-pane key="2" tab="参数联想" force-render></a-tab-pane>
            </a-tabs>
          </div>
        </div>
        <div class="lianxiang-body">
          111111
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import {
  BarsOutlined,
  SendOutlined,
  CheckCircleOutlined,
  RedoOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue';

let vditorInstance: Vditor | null = null;
const headings = ref<{ text: string, line: number }[]>([]);
const showDialog = ref(false);
const aiResultRef = ref()
const isShowLianXiang = ref(false)
const lianXiangRef = ref()
const lianxiangActiveKey = ref('1')

const toShowMarkDownDialog = () => {
  const position: any = vditorInstance?.getCursorPosition()
  console.log('position is ', position, aiResultRef.value)
  aiResultRef.value.style.top = (position?.top + 36) + 'px'
  isShowDaGang.value = true
}

const daGangSearchText = ref()
const daGangAiText = ref()
const daGangText = ref('')
const isShowDaGang = ref(false)
const isStartLianXiang = ref(false)

const toStartLianXiang = () => {
  isStartLianXiang.value = true
}

onMounted(() => {
  vditorInstance = new Vditor('vditor', {
    height: '80vh',
    width: '1200px',
    mode: 'ir', // 即时渲染模式
    toolbarConfig: {
      pin: true,
    },
    toolbar: [
      'emoji', 'headings', 'bold', 'italic', 'strike', 'link', '|',
      'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
      'quote', 'line', 'code', 'inline-code', 'insert-before', 'insert-after', '|',
      'upload', 'record', 'table', '|',
      'undo', 'redo', '|',
      {
        name: 'smart-outline',
        tip: '智能大纲',
        icon: '<svg viewBox="0 0 24 24" width="24" height="24"><path d="M12 2L2 7h20L12 2zm0 2.18L18.09 7H5.91L12 4.18zM2 9v11h20V9H2zm2 2h16v7H4v-7z"/></svg>',
        click: () => {
          toShowMarkDownDialog()
        }
      }
    ],
    upload: {
      url: 'http://localhost:3000/upload',
      fieldName: 'file',
      format: (files, responseText) => {
        const response = JSON.parse(responseText);
        if (response.code === 0) {
          // 返回第一个成功上传的文件 URL
          return responseText
        } else {
          throw new Error('Upload failed');
        }
      },
      error: (message) => {
        console.error('Upload error:', message);
      }
    },
    cache: {
      id: 'vditor',
    },
    after: () => {
      extractHeadings();
    },
    input: (value: string) => {
      console.log('🚀 ~ onMounted ~ value:', value)
      extractHeadings();
    },
    select (md) {
      console.log('用户选了一段文字', md)
      isShowLianXiang.value = true
      const position: any = vditorInstance?.getCursorPosition()
      console.log('position is ', position, aiResultRef.value)
      lianXiangRef.value.style.top = (position?.top + 8) + 'px'
      lianXiangRef.value.style.left = (position?.left) + 'px'
    }
  });
});

function extractHeadings() {
  if (!vditorInstance) return;
  const content = vditorInstance.getValue();
  const lines = content.split('\n');
  headings.value = lines.map((line, index) => {
    const match = line.match(/^(#{1,6})\s+(.*)/);
    if (match) {
      return { text: match[2], line: index };
    }
    return null;
  }).filter(Boolean) as { text: string, line: number }[];
}

function scrollToHeading(heading: { text: string, line: number }) {
  if (!vditorInstance) return;
  const editorElement = document.querySelector('.vditor-ir');
  if (!editorElement) return;
  const lines = editorElement.querySelectorAll('h1, h2, h3, h4, h5, h6');
  const headingElement = Array.from(lines).find(el => el.textContent?.trim() === heading.text);
  if (headingElement) {
    headingElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}

function streamInputToVditor(text: string, interval: number = 100) {
  if (!vditorInstance) return;

  let index = 0;
  const length = text.length;

  const intervalId = setInterval(() => {
    if (index < length) {
      vditorInstance?.setValue(text.slice(0, index));
      index++;
    } else {
      clearInterval(intervalId);
      extractHeadings();
    }
  }, interval);
}

const daGangInputEvent = (event) => {
  console.log('🚀 ~ daGangInputEvent ~ event:', event, daGangAiText)
  daGangText.value = '圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了圣诞节分厘卡就打算离开房间都是离开房间是立刻搭街坊卡拉的时间弗兰克但是上了大家分厘卡电视机分厘卡是拉开圣诞节分厘卡电视机弗兰克但是附件两款都是积分了肯定是解放了'
}

function toShowMarkdown() {
  const markdownText = `
  # 这是一个标题

  ## 这是一个二级标题

  ### 这是一个三级标题

  **这是加粗的文本**

  *这是斜体的文本*

  ~~这是删除线文本~~

  > 这是一个引用块

  - 这是一个无序列表项
    - 这是一个嵌套的无序列表项

  1. 这是一个有序列表项
  2. 这是另一个有序列表项

  [这是一个链接](https://www.example.com)

  ![这是一个图片](https://www.example.com/image.jpg)

  \`这是行内代码\`

  <table>
    <tr>
        <th rowspan="2">合并行</th>
        <th>列1</th>
        <th>列2</th>
    </tr>
    <tr>
        <td>数据1</td>
        <td>数据2</td>
    </tr>
    <tr>
        <td>数据3</td>
        <td colspan="2">合并列</td>
    </tr>
</table>
  `;

  streamInputToVditor(markdownText);
}

function closeDialog() {
  showDialog.value = false;
}
</script>

<style scoped>
.editor-container {
  display: flex;
  justify-content: center;
  /* align-items: center; */
  height: 100vh;
  position: relative;
  width: 1400px;
  margin-top: 50px;
}

.vditor {
  width: 80%;
  text-align: left;
}

.sidebar {
  width: 200px;
  padding-left: 50px;
}

.sidebar ul {
  list-style: none;
  padding: 0;
}

.sidebar li {
  cursor: pointer;
  margin-bottom: 5px;
  /* color: blue;
  text-decoration: underline; */
  font-weight: 700;
  font-size: 16px;
}

.dialog {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.dialog-content input {
  margin-right: 10px;
  padding: 5px;
}

.input-prefix {
  margin-right: 5px;
}

.input-suffix {
  margin-left: 5px;
}
.ai-result {
  position: absolute;
  width: 1160px;
  left: 20px;
  border-radius: 6px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
  z-index: 9999;
  background: #fff;
}
.title-input {
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 10px;
  border-top: 1px solid #ccc;
}
.dagang-icon {
  font-size: 22px;
  cursor: pointer;
}
.dagang-input {
  width: 999px;
  margin-right: 5px;
  border: none;
  outline: none;
  background: #fff;
}
.dagang-ai-content {
  width: 100%;
}
.dagang-ai-text {
  width: 100%;
  padding: 10px;
}
.dagang-ai-button {
  font-size: 22px;
  display: flex;
  flex-direction: row-reverse;
  padding: 0 10px;
}
.dagang-res-button {
  margin-left: 10px;
  cursor: pointer;
}
.lianxiang {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 9999;
}
.lianxiang-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.lianxiang-icon img {
  width: 100%;
  height: 100%;
}
.lianxiang-content {
  background: #fff;
  width: 500px;
  height: 500px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
  padding: 10px;
}
.lianxiang-header {
  display: flex;
  align-items: center;
}
</style> 
<style>
.vditor-reset {
  position: relative;
}
</style>